<template>
    <div class="snow-page">
        <a-layout>
            <a-layout-sider style="min-width: 250px;">
                <div>
                    <h4 style="margin: 10px">企业列表

                        <a-input v-model="serachValue" style="width:180px" placeholder="关键字搜索" allow-clear />
                        <a-button type="primary" @click="InputEvent">
                            <template #icon>
                                <icon-search />
                            </template>
                        </a-button>
                    </h4>
                    <a-tree :data="treeNodes" :field-names="{
                        key: 'id',
                        title: 'name',
                        children: 'children'
                    }" @select="clickTreeNode" style="margin-left: 5px;max-height: 100vh;overflow: auto;">
                        <template #title="{ name }">
                            <a-tooltip :content="name">
                                <div class="marquee">
                                    <icon-common />
                                    {{ name }}
                                </div>
                            </a-tooltip>
                        </template>
                    </a-tree>
                </div>
            </a-layout-sider>
            <a-layout>
                <a-layout-content>
                    <div class="snow-inner-page">
                        <a-form :model="formData.form" :label-col-props="{ span: 10 }" :wrapper-col-props="{ span: 14 }"
                            ref="formRef">
                            <a-row :gutter="24">
                                <a-col :span="8">
                                    <a-form-item field="node_id" label="网关">
                                        <a-select v-model="formData.form.node_id" placeholder="选择网关" allow-clear>
                                            <a-option v-for="(item, index) in sbList" :key="index"
                                                :value="item.id">{{ item.name }}</a-option>
                                        </a-select>
                                    </a-form-item>

                                </a-col>
                                <a-col :span="8">
                                    <a-form-item field="name" label="触发器名称">
                                        <a-input v-model="formData.form.name" placeholder="请输入名称" allow-clear />
                                    </a-form-item>

                                </a-col>
                                <a-col :span="8">
                                    <a-form-item field="sensor_name" label="传感器名称">
                                        <a-input v-model="formData.form.sensor_name" placeholder="请输入传感器名称"
                                            allow-clear />
                                    </a-form-item>

                                </a-col>
                                <a-col :span="10">
                                    <a-space>
                                        <a-button type="primary" @click="onSearch">
                                            <template #icon>
                                                <icon-search />
                                            </template>
                                            <template #default>查询</template>
                                        </a-button>
                                        <a-button @click="onReset">
                                            <template #icon>
                                                <icon-refresh />
                                            </template>
                                            <template #default>重置</template>
                                        </a-button>
                                        <a-button type="primary" @click="onAdd">
                                            <template #icon>
                                                <icon-PlusOutlined />
                                            </template>
                                            <template #default>新增</template>
                                        </a-button>
                                    </a-space>
                                </a-col>
                            </a-row>
                        </a-form>
                        <a-table :data="tableData" row-key="id" :pagination="false">
                            <template #columns>
                                <a-table-column title="名称">
                                    <template #cell="{ record }">
                                        {{ record.name }}
                                    </template>
                                </a-table-column>
                                <a-table-column title="关联传感器">
                                    <template #cell="{ record }">
                                        {{ (record.from_sensor_name) }}
                                    </template>
                                </a-table-column>

                                <a-table-column title="触发条件类型">
                                    <template #cell="{ record }">
                                        {{ record.data.iot_trigger_condition_type }}
                                    </template>
                                </a-table-column>
                                <a-table-column title="参数">
                                    <template #cell="{ record }">
                                        {{ record.condition_params }}
                                    </template>
                                </a-table-column>

                                <a-table-column title="执行类型">
                                    <template #cell="{ record }">
                                        {{ format49(record.iot_trigger_action_type) }}
                                    </template>
                                </a-table-column>
                                <a-table-column title="循环间隔(s)">
                                    <template #cell="{ record }">
                                        {{ (record.trigger_inteval_time) }}
                                    </template>
                                </a-table-column>

                                <a-table-column title="状态">
                                    <template #cell="{ record }">
                                        <a-tag color="arcoblue" v-if="record.data.iot_trigger_status == '正常'">{{
                                            record.data.iot_trigger_status
                                            }}</a-tag>
                                        <a-tag color="red" v-else>{{ record.data.iot_trigger_status }}</a-tag>
                                    </template>
                                </a-table-column>


                                <a-table-column title="操作" align="center" fixed="right">
                                    <template #cell="{ record }">
                                        <a-space>
                                            <a-button size="mini" type="primary" @click="onEdit(record)">修改</a-button>

                                            <a-button size="mini" type="primary" status="danger"
                                                @click="onDelete2(record)">删除</a-button>

                                        </a-space>
                                    </template>
                                </a-table-column>
                            </template>
                        </a-table>
                        <a-pagination :total="total" style="margin-top: 10px" @change="changePage" />
                    </div>
                </a-layout-content>
            </a-layout>
        </a-layout>
    </div>
</template>

<script setup lang="ts">
// import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
// import dynamicRoutes from "@/mock/_data/system_menu";
import { Modal, Message } from "@arco-design/web-vue";
import { getAllqiyeAPI } from "@/api/modules/qiye/index";
import { getProjectAPI } from "@/api/modules/project/index";
import { getDictBycodeAPI } from "@/api/modules/dictionary/index";
import { gettriggerListAPI, deletetriggerAPI } from "@/api/modules/trigger/index";
import { useUserInfoStore } from "@/store/modules/user-info";
import { onMounted, ref } from "vue";
const router = useRouter();
onMounted(() => {
    getDictBycodeAPIfun();
    getDictBycodeAPIfun2();
    getDictBycodeAPIfun3();
    getProinit();
    getInit();
    init();
});


const options49 = ref([]);
async function getDictBycodeAPIfun3() {
    let res = await getDictBycodeAPI(49);
    if (res.status == 2) {
        options49.value = res.data;
    }
}


function format49(val) {
    if (val) {
        let resArr = []
        let arr = val.split(",")
        for (let i = 0; i < arr.length; i++) {
            let obj = options49.value.filter((e) => {
                return e.id == arr[i]
            })
            resArr.push(obj[0].name)

        }

        return resArr
    }
}


const sbList = ref([])

async function getProinit() {
    let form = {
        name: "",
        scene_id: "",
        scene_ids: [],

    };
    let obj = {
        paged: 1,
        pageSize: 500
    }
    let res = await getProjectAPI(obj, form);

    sbList.value = [];
    if (res.status == 2) {

        sbList.value = res.data.data;
    }
}



const serachValue = ref("");
const treeNodes = ref([]);



function InputEvent() {
    if (serachValue.value) {
        treeNodes.value = [];
        let arr = [];
        for (let i = 0; i < optionData.value.length; i++) {
            if (optionData.value[i].name.includes(serachValue.value)) {
                arr.push(optionData.value[i])
            }
        }
        treeNodes.value = generateTreeNodes(arr);
    } else {
        let obj = {}
        getAllqiyeAPI(obj).then(res => {
            treeNodes.value = generateTreeNodes(res.data);
        })
    }
}

const optionData = ref([])
async function getInit() {
    let obj = {};
    let res = await getAllqiyeAPI(obj);
    if (res.status == 2) {
        treeNodes.value = generateTreeNodes(res.data);
        optionData.value = res.data;
    }
}

const options558 = ref([]);
async function getDictBycodeAPIfun2() {
    let res = await getDictBycodeAPI(558);
    if (res.status == 2) {
        options558.value = res.data;
    }
}


function generateTreeNodes(data) {
    const nodeMap = new Map();
    const rootNodes = [];

    // First pass: create nodes and store them in a map
    data.forEach(item => {
        const node = {
            id: item.id,
            name: item.name ? item.name : item.cq_company_short_name,
            children: [],
            data: item // Store all original data
        };
        nodeMap.set(item.cq_company_code, node);
    });

    // Second pass: build the tree structure
    data.forEach(item => {
        const node = nodeMap.get(item.cq_company_code);
        if (item.cq_parent_code === "0") {
            rootNodes.push(node);
        } else {
            const parentNode = nodeMap.get(item.cq_parent_code);
            if (parentNode) {
                parentNode.children.push(node);
            } else {
                console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
                rootNodes.push(node); // Add to root if parent not found
            }
        }
    });

    return rootNodes;
}

function clickTreeNode(selectedKeys, extra) {
    // const allIds = [];
    // getAllChildrenIds(extra.node, allIds);
    formData.form.scene_id = selectedKeys[0]
    init();
}

// function getAllChildrenIds(node, idsArray) {
//     // 把当前节点的 id 加入数组
//     idsArray.push(node.id); // 如果有子节点，则递归处理
//     if (node.children && node.children.length > 0) {
//         node.children.forEach(child => {
//             getAllChildrenIds(child, idsArray);
//         });
//     }
// }
const total = ref(0);
async function init() {
    let res = await gettriggerListAPI(formData, formData.form);
    total.value = 0
    tableData.value = [];
    if (res.status == 2) {
        total.value = res.data.totalCount;
        tableData.value = res.data.data;
    }
}
function changePage(page) {
    formData.paged = page;
    init();
}
const tableData = ref([]);
const formData = reactive({
    form: {
        name: "",
        node_id: "",
        scene_id: "",
        sensor_name: ""
    },
    paged: 1,
    pageSize: 10
});

const formRef = ref();
const onReset = () => {
    formRef.value.resetFields();
    init();
};

async function onSearch() {
    init();
}

const options81 = ref([]);
async function getDictBycodeAPIfun() {
    // let obj={}
    let res = await getDictBycodeAPI(81);
    if (res.status == 2) {
        options81.value = res.data;
    }
}




function onAdd() {
    let stores = useUserInfoStore();
    stores.removeSharedObject();
    router.push({ path: "/project/cfqAdd" });
}

const onEdit = (row: any) => {
    let stores = useUserInfoStore();
    stores.setSharedObject(row);
    router.push({ path: "/project/cfqAdd" });
};

const onDelete2 = (row: any) => {
    Modal.warning({
        title: "提示",
        content: "确定删除？",
        hideCancel: false,
        closable: true,
        onOk: async () => {
            try {
                let res = (await deletetriggerAPI(row.id)) as any;
                if (res.status == 2) {
                    Message.success("删除成功");
                } else {
                    Message.error(res.statusMsg);
                }
                init();
            } catch { }
        }
    });
};
</script>

<style lang="scss">
.arco-modal-body {
    text-align: center !important;
}

.marquee {
    white-space: nowrap;
    /* 确保文本在一行内显示 */
    overflow: hidden;
    /* 隐藏溢出的内容 */
    text-overflow: ellipsis;
    /* 使用打点显示溢出的文本 */
    width: 100%;
    /* 设置宽度，根据需要调整 */
    max-width: 200px;
    /* 最大宽度，根据需要调整 */

    box-sizing: border-box;
    /* 防止宽度计算包含边框和内边距 */
}
</style>